package org.dromara.genealogy.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.TreeBuildUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.bo.SysDeptBo;
import org.dromara.system.domain.vo.SysDeptVo;
import org.springframework.stereotype.Service;
import org.dromara.genealogy.domain.bo.GeDirectoryBo;
import org.dromara.genealogy.domain.vo.GeDirectoryVo;
import org.dromara.genealogy.domain.GeDirectory;
import org.dromara.genealogy.mapper.GeDirectoryMapper;
import org.dromara.genealogy.service.IGeDirectoryService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 目录管理Service业务层处理
 *
 * @author qianjm
 * @date 2025-08-18
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class GeDirectoryServiceImpl implements IGeDirectoryService {

    private final GeDirectoryMapper baseMapper;

    /**
     * 查询目录管理
     *
     * @param id 主键
     * @return 目录管理
     */
    @Override
    public GeDirectoryVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询目录管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 目录管理分页列表
     */
    @Override
    public TableDataInfo<GeDirectoryVo> queryPageList(GeDirectoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<GeDirectory> lqw = buildQueryWrapper(bo);
        Page<GeDirectoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的目录管理列表
     *
     * @param bo 查询条件
     * @return 目录管理列表
     */
    @Override
    public List<GeDirectoryVo> queryList(GeDirectoryBo bo) {
        LambdaQueryWrapper<GeDirectory> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<GeDirectory> buildQueryWrapper(GeDirectoryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GeDirectory> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(GeDirectory::getSorted);
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), GeDirectory::getCode, bo.getCode());
        lqw.like(StringUtils.isNotBlank(bo.getName()), GeDirectory::getName, bo.getName());
        return lqw;
    }

    /**
     * 新增目录管理
     *
     * @param bo 目录管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(GeDirectoryBo bo) {
        GeDirectory add = MapstructUtils.convert(bo, GeDirectory.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改目录管理
     *
     * @param bo 目录管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(GeDirectoryBo bo) {
        GeDirectory update = MapstructUtils.convert(bo, GeDirectory.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GeDirectory entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除目录管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Boolean checkUnique(GeDirectoryBo bo) {
        List<GeDirectory> lqcw = new LambdaQueryChainWrapper<>(baseMapper).eq(GeDirectory::getGeId, bo.getGeId()).eq(GeDirectory::getCode, bo.getCode()).list();
        return CollectionUtil.isEmpty(lqcw)?true:false;
    }

    /**
     * 查询族谱目录树结构信息
     *
     * @param bo 目录信息
     * @return 目录树信息集合
     */
    @Override
    public List<Tree<Long>> selectDirecTreeList(GeDirectoryBo bo) {
        LambdaQueryWrapper<GeDirectory> lqw = buildQueryWrapper(bo);
        List<GeDirectory> list = baseMapper.selectList(lqw);
        return buildDeptTreeSelect(list);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param direcList 目录列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<Long>> buildDeptTreeSelect(List<GeDirectory> direcList) {
        if (CollUtil.isEmpty(direcList)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.buildMultiRoot(
            direcList,
            GeDirectory::getId,
            GeDirectory::getParentId,
            (node, treeNode) ->{
                treeNode.setId(node.getId())
                    .setParentId(node.getParentId())
                    .setName(node.getName())
                    .setWeight(node.getSorted())
                    .putExtra("disabled", SystemConstants.DISABLE.equals(node.getDelFlag()));
                treeNode.putExtra("code", node.getCode());
                treeNode.putExtra("geId", node.getGeId());
            }
        );
    }
}
